<template>
  <div class="app-container">
    <div class="contentBox">
      <div class="searchBox">
        <el-form :model="queryParams" ref="queryRef" :inline="true" @submit.prevent>
          <el-form-item prop="companyName" style="margin: 0 6px 0 0;">
            <el-input
                class="inputBox"
                v-model="queryParams.companyName"
                placeholder="请输入企业名称"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item style="margin: 0 6px 0 0;">
            <el-button class="normalFormBg searchBtn" icon="Search" @click="handleQuery"></el-button>
            <el-button class="normalFormBg searchBtn" icon="Refresh" @click="resetQuery"></el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-row :gutter="10" style="margin: 16px 0;">
        <el-col :span="1.5">
          <div class="normalBtn pageFlex pageFlexCenter" @click="toPage('/gasManage/defaultSetting/company-info/dataManage/')" v-hasPermi="['gasManage:defaultSetting:companyInfo:add']">
            <img src="@/assets/images/plus.png" class="normalBtn_icon">
            <div class="normalBtn_text">新增</div>
          </div>
        </el-col>
      </el-row>
      <el-table
        v-loading="loading"
        :data="dataList"
        border>
        <el-table-column prop="companyName" label="企业名称" width="150" :show-overflow-tooltip="true" fixed="left"></el-table-column>
        <el-table-column prop="thumb" label="LOGO" width="80" align="center">
          <template #default="scope">
            <div class="tableImgBox1">
              <el-image class="img" fit="contain" lazy :src="setCoverUrl(scope.row.thumb)"
                @click="handlePreviewShow(setCoverUrl(scope.row.thumb))" v-if="scope.row.thumb" />
              <div class="emptyBox" v-else>暂无图标</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="companyType" label="企业类型" width="150">
          <template #default="scope">
            <div v-for="(item, index) in meter_company_type" :key="index" v-show="item.value == scope.row.companyType">
              <el-tag :type="item.elTagType" v-if="item.elTagType">{{ item.label }}</el-tag>
              <div v-else>{{ item.label }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="contacts" label="联系人" width="150" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="telephone" label="联系电话" width="150" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="creditCode" label="统一社会信用代码" width="150">
          <template #default="scope">
            <div class="pageFlex pageAlignCenter" v-if="scope.row.creditCode">
              <div class="copyText textOverflow1">{{ scope.row.creditCode }}</div>
              <img src="@/assets/images/copy.png" class="copyIcon" @click="copyNow(scope.row.creditCode)">
            </div>
            <div v-else>暂无</div>
          </template>
        </el-table-column>
        <el-table-column prop="regyear" label="注册日期" width="100" :show-overflow-tooltip="true">
          <template #default="scope">
            <div>{{setTimeFormat(scope.row.regyear)}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="联系地址" width="200" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="mail" label="企业电子邮件" width="200" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="postcode" label="联系邮编" width="100" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="fax" label="传真" width="200" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="keyword" label="搜索关键字" width="150" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="homepage" label="公司主页（网址）" width="220" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="introduce" label="介绍" width="300" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="isEnable" label="审核状态" width="150">
          <template #default="scope">
            <div v-for="(item, index) in meter_company_validatedtype" :key="index" v-show="item.value == scope.row.validated">
              <el-tag :type="item.elTagType" v-if="item.elTagType">{{ item.label }}</el-tag>
              <div v-else>{{ item.label }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="450" align="center" fixed="right">
          <template #default="scope">
            <div class="pageFlex pageFlexCenter" style="width: 100%;">
              <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:defaultSetting:companyInfo:devService']" @click="handleDevService(scope.row.id)">
                <img src="@/assets/images/developService.png" class="img">
                <div class="text">开发服务</div>
              </div>
              <div class="pageFlex pageFlexCenter btnSetBox" @click="toPage('/gasManage/defaultSetting/company-info/dataManage/', scope.row)">
                <img src="@/assets/images/fileManage.png" class="img">
                <div class="text">资料管理</div>
              </div>
              <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:defaultSetting:companyInfo:validate']" @click="handleValidated(scope.row)">
                <img src="@/assets/images/companySet.png" class="img">
                <div class="text">企业认证审核</div>
              </div>
              <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:defaultSetting:companyInfo:history']" @click="toPage('/gasManage/defaultSetting/company-info/examineRecord/'+scope.row.id)">
                <img src="@/assets/images/fileManage.png" class="img">
                <div class="text">审核记录</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据"/>
        </template>
      </el-table>
      <div class="pageFlex pageAlignCenter pageSpaceBetween" style="margin-top: 20px;">
        <div class="totalText">共计 {{total}} 条</div>
        <el-pagination background layout="prev, pager, next" :total="total" :current-page="queryParams.page" :page-size="queryParams.pageSize" @current-change="handleCurrentChange"/>
      </div>
    </div>
    <el-drawer v-model="modalShow" direction="rtl" size="615" :title="modalTitle">
      <div class="modalBox">
        <div class="modalBoxContent">
          <el-form
              ref="formRef"
              class="formContent"
              label-width="110"
              :model="form"
              :rules="rules"
          >
            <div style="width: 100%;" v-if="modalTitle === '开发服务'">
              <div class="formContentTop pageFlex pageAlignCenter">
                <div class="line"></div>
                <div class="title">开发服务信息</div>
              </div>
              <div class="formContentCenter bgFF">
                <el-form-item label="APPID" prop="appId">
                  <el-text class="disabledBox">{{ form.appId }}</el-text>
                </el-form-item>
                <el-form-item label="密钥" prop="appSecret">
                  <el-text class="disabledBox">{{ form.appSecret }}</el-text>
                </el-form-item>
                <el-form-item label="商家代码" prop="merchantCode">
                  <el-text class="disabledBox">{{ form.merchantCode }}</el-text>
                </el-form-item>
              </div>
            </div>
            <div style="width: 100%;" v-else>
              <div class="formContentTop pageFlex pageAlignCenter">
                <div class="line"></div>
                <div class="title">公司信息审核</div>
              </div>
              <div class="formContentCenter bgFF">
                <el-form-item label="资料审核状态" label-position="top" prop="status">
                  <el-select v-model="form.status" placeholder="请选择状态">
                    <el-option v-for="dict in meter_company_validatedtype" :key="dict.value" :label="dict.label"
                      :value="dict.value" :disabled="['0', '1'].includes(dict.value)" />
                  </el-select>
                </el-form-item>
                <el-form-item label="审核意见" label-position="top" prop="results">
                  <editor v-model="form.results" :height="400" v-if="modalShow"/>
                </el-form-item>
              </div>
            </div>
          </el-form>
        </div>
        <div class="lineBox"></div>
        <div class="bottomBox pageFlex pageFlexCenter">
          <el-button type="primary" :loading="submitLoading" @click="updateDevService" v-if="modalTitle === '开发服务'">重新获取开发服务内容</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitNow" v-else>确认提交</el-button>
        </div>
        <el-button type="primary" :loading="formLoading" class="modalLoadingBox" v-if="formLoading">加载数据中</el-button>
      </div>
    </el-drawer>
    <el-image-viewer :url-list="srcList" @close="handlePreviewClose" v-if="showPreview"/>
  </div>
</template>
<script setup>
import {computed, onMounted} from 'vue';
import { useRouter } from 'vue-router';
import { searchManufacturerApi, examineManufacturerApi, searchManufacturerByIdApi, updateAppIdAndKeyApi } from '@/api/gasManage/defaultSetting/companyInfo';
const { proxy } = getCurrentInstance();
const { meter_company_validatedtype, meter_company_type } = proxy.useDict("meter_company_validatedtype", "meter_company_type");
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const router = useRouter();
const setTimeFormat = computed(()=>{
  return val=>{
    if(val){
      let date = new Date(val);
      return date.toLocaleDateString();
    }
    return '暂无'
  }
})
// -----------------------------查询----------------------
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  companyName: ''
})
const loading = ref(false);
const total = ref(0);
const dataList = ref([]);
const showPreview = ref(false);
const srcList = ref([])
const setCoverUrl = computed(()=>{
  return url => {
    if(url){
      return baseUrl+url
    }
    return  ''
  }
})
function handleQuery(){
  queryParams.value.pageNum = 1;
  getList();
}
function resetQuery(){
  proxy.resetForm("queryRef");
  handleQuery();
}
async function getList(){
  loading.value = true;
  let data = await getCompanyInfoApi(queryParams.value);
  if(data && Array.isArray(data)){
    dataList.value = data;
  }else{
    dataList.value = [];
  }
  loading.value = false;
}
function getCompanyInfoApi(params){
  return new Promise(resolve => {
    searchManufacturerApi(params).then(res => {
      total.value = Number(res.total);
      resolve(Array.isArray(res.rows) ? res.rows : []);
    }).catch(() => {resolve(false)})
  })
}
function handleCurrentChange(e){
  queryParams.value.pageNum = e;
  getList();
}
function copyNow(code){
  navigator.clipboard.writeText(code).then(()=>{
    proxy.$modal.msgSuccess('复制成功！');
  });
}
function toPage(link, row){
  let url = link;
  if(row){
    url += row.id
  }
  router.push(url);
}
function handlePreviewShow(link){
  srcList.value = [link];
  showPreview.value = true;
}
function handlePreviewClose(){
  showPreview.value = false;
  srcList.value = [];
}
// ----------------------弹窗---------------------
const modalShow = ref(false);
const modalTitle = ref('');
const submitLoading = ref(false);
const form = ref({
  status: '1',
  results: ''
})
const rules = ref({
  status: [{ required: true, message: "请选择状态", trigger: "blur" }],
})
function handleModalShow(name){
  modalTitle.value = name;
  modalShow.value = true;
}
function handleModalHide(){
  modalShow.value = false;
}
function submitNow(){
  if(submitLoading.value) return;
  proxy.$refs["formRef"].validate(valid=>{
    if(valid){
      submitLoading.value = true;
      if(modalTitle.value === '企业认证审核'){
        examineNow()
      }
    }else{
      proxy.$modal.alertWarning('有必填选项未填写，请查看！');
    }
  })
}
// ----------------------开发服务---------------------
const formLoading = ref(false);
async function handleDevService(id){
  proxy.resetForm('formRef');
  form.value.id = id;
  handleModalShow('开发服务');
  formLoading.value = true;
  let data = await getCompanyInfoByIdApi(id);
  if(data){
    form.value.appId=data.appId;
    form.value.appSecret=data.appSecret;
    form.value.merchantCode=data.merchantCode;
    formLoading.value = false;
  }else{
    formLoading.value = false;
    setTimeout(()=>{
      handleModalHide();
    }, 500)
  }
}
function getCompanyInfoByIdApi(id){
  return new Promise((resolve, reject) => {
    searchManufacturerByIdApi(id).then(res => {
      resolve(res.data)
    }).catch(()=>{
      resolve(false);
    })
  })
}
// ---------------------重新获取开发服务内容-----------------------
function updateDevService(){
  submitLoading.value = true;
  updateAppIdAndKeyApi({
    id: form.value.id,
  }).then(() => {
    submitLoading.value = false;
    proxy.$modal.msgSuccess('重新获取开发服务成功！');
    handleDevService(form.value.id);
  }).catch(()=>{
    submitLoading.value = false;
  })
}
// ----------------------企业认证审核---------------------
function handleValidated(row){
  proxy.resetForm('formRef');
  form.value.status = String(row.validated);
  form.value.manufacturerId = row.id;
  handleModalShow('企业认证审核');
}
async function examineNow(){
  let data = JSON.parse(JSON.stringify(form.value));
  data.status = Number(data.status);
  examineManufacturerApi(data).then(() => {
    submitLoading.value = false;
    handleModalHide();
    proxy.$modal.msgSuccess('审核处理成功');
    getList();
  }).catch(()=>{
    submitLoading.value = false;
  })
}
onMounted(()=>{
  getList();
})
</script>
<style lang="scss" scoped>
@import "@/assets/styles/public.scss";
:deep(.el-dialog){
  &.is-align-center{
    margin: auto;
    position: relative;
    top: 40%;
    transform: translateY(-40%);
  }
}
:deep(.el-input){
  .el-input__wrapper{
    background-color: $formBgSet;
    box-shadow: none;
  }
}
.copyText{
  width: calc(100% - 14px);
  height: 14px;
  line-height: 14px;
  font-weight: 400;
  font-size: 14px;
  color: #1D2129;
}
.copyIcon{
  width: 14px;
  height: 14px;
  margin-left: 10px;
  cursor: pointer;
  user-select: none;
}
.app-container{
  width: 100%;
  min-height: calc(100vh - 66px);
  background: #F8F8F9;
}
.contentBox{
  width: 100%;
  min-height: $pageMinHeight;
  background-color: #FFFFFF;
  border-radius: 5px;
  box-sizing: border-box;
  padding: 12px;
  .searchBtn{
    width: 32px;
    height: 32px;
    font-size: 12px;
    padding: 0;
    border: none;
    margin: 0 6px 0 0px;
  }
  .btnSetBox{
    padding: 0 10px;
    box-sizing: border-box;
    border-right: 1px solid $borderColor;
    cursor: pointer;
    .text{
      height: 16px;
      line-height: 16px;
      color: var(--el-color-primary);
    }
    .img{
      width: 16px;
      height: 16px;
      margin-right: 2px;
    }
    &:last-child{
      border-right: none;
    }
  }
  .totalText{
    height: 22px;
    font-weight: 400;
    font-size: 14px;
    color: #1D2129;
    line-height: 22px;
  }
}
:deep(.el-drawer){
  .el-drawer__header{
    margin: 0;
    padding-bottom: 20px;
  }
  .el-drawer__body{
    padding: 0;
  }
}
</style>